<template>
  <div class="standard-management-container">
    <h1 class="page-title">标准管理</h1>
    
    <div class="search-and-buttons">
      <input
        type="text"
        class="search-input"
        placeholder="请输入搜索关键字"
        v-model="searchText"
      />

      <div class="buttons">
        <button
          class="batch-delete-button"
          @click="batchDelete"
          :disabled="!selectedItems.length"
        >
          批量删除
        </button>
        <button class="add-button" @click="showDialog">添加</button>
        <button class="import-excel-button" @click="triggerFileInput">
          导入Excel
        </button>
        <button class="export-excel-button" @click="exportToExcel">
          导出Excel
        </button>
        <input
          type="file"
          ref="fileInput"
          @change="importFromExcel"
          style="display: none"
          accept=".xlsx, .xls"
        />
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog title="添加标准" :visible.sync="dialogVisible">
      <el-form :model="form">
        <el-form-item label="大类" :label-width="formLabelWidth">
          <el-input v-model="form.staType" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品名" :label-width="formLabelWidth">
          <el-input v-model="form.projectName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="标准编号（含年号）" :label-width="formLabelWidth">
          <el-input v-model="form.staGB" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="标准名称" :label-width="formLabelWidth">
          <el-input v-model="form.staName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addProject">确 定</el-button>
      </div>
    </el-dialog>

    <table class="standards-table">
      <thead>
        <tr>
          <th>
            <input
              type="checkbox"
              @change="toggleSelectAll"
              v-model="selectAll"
            />
          </th>
          <th>序号</th>
          <th>大类</th>
          <th>产品名</th>
          <th>标准编号</th>
          <th>标准名称</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in filteredItems" :key="item.staId">
          <td>
            <input
              type="checkbox"
              v-model="selectedItems"
              :value="item.staId"
            />
          </td>
          <td>{{ index + 1 }}</td>
          <td>{{ item.staType }}</td>
          <td>{{ item.staName }}</td>
          <td>{{ item.staGB }}</td>
          <td>{{ item.staName }}</td>
          <td>
            <span class="action-link">
              <a
                href="javascript:void(0);"
                class="view-link"
                @click="showItem(item)"
                >查看项目</a
              >
            </span>
            <span class="action-divider">|</span>
            <span class="action-link">
              <a
                href="javascript:void(0);"
                class="delete-link"
                @click="deleteItem(item)"
                >删除</a
              >
            </span>
            <span class="action-divider">|</span>
            <span class="action-link">
              <a
                href="javascript:void(0);"
                class="sample-link"
                @click="showSample(item)"
                >查看样品</a
              >
            </span>
            <!-- <button class="view-item-button" @click="showItem(item)">查看项目</button>
            <button class="delete-item-button" @click="deleteItem(item)">删除</button>
            <button class="view-sample-button" @click="showSample(item)">查看样品</button> -->
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import * as XLSX from "xlsx";

export default {
  name: "StandardManagement",
  data() {
    return {
      items: [
        // 示例数据，实际数据应从后端获取
        // {
        //   id: 1,
        //   category: "无源医疗器械",
        //   productName: "医用防护口罩",
        //   standardNumber: "GB 19083-2023",
        //   standardName: "医用防护口罩",
        // },
        // {
        //   id: 2,
        //   category: "无源医疗器械",
        //   productName: "医用一次性防护服",
        //   standardNumber: "GB 19083-2023",
        //   standardName: "医用一次性防护服",
        // },
        // {
        //   id: 3,
        //   category: "无源医疗器械",
        //   productName: "医用敷料",
        //   standardNumber: "GB 16886-2023",
        //   standardName: "��用敷料",
        // },
        // ... 其他数据行
      ],
      searchText: "",

      dialogVisible: false,
      form: {
        category: "",
        productName: "",
        standardNumber: "",
        standardName: "",
      },
      formLabelWidth: "120px",
      selectedItems: [],
      selectAll: false,
    };
  },
  computed: {
    filteredItems() {
      if (!this.searchText.trim()) {
        return this.items;
      }
      const searchTerm = this.searchText.trim().toLowerCase();
      return this.items.filter((item) => {
        // 搜索所有相关字段
        return (
          (item.staType && item.staType.toLowerCase().includes(searchTerm)) ||
          (item.projectName && item.projectName.toLowerCase().includes(searchTerm)) ||
          (item.staGB && item.staGB.toLowerCase().includes(searchTerm)) ||
          (item.staName && item.staName.toLowerCase().includes(searchTerm))
        );
      });
    },
  },
  created() {
    this.fetchData();
  },
  methods: {
    showDialog() {
      this.dialogVisible = true;
    },
    addProject() {
      // 在这里处理添加逻辑，例如发送请求到服务器
      const formData = {
        staType: this.form.staType,
        staGB: this.form.staGB,
        staName: this.form.staName,
      };
      this.$http
        .put("/AddStandard", formData)
        .then((response) => {
          // 处理响应
          console.log(response.data);
          this.dialogVisible = false; // 关闭对话框
          this.$message({
            message: "添加标准成功",
            type: "success",
          });
          this.fetchData(); // 添加成功后刷新数据
        })
        .catch((error) => {
          // 处理错误
          console.error(error);
          this.$message.error("添加标准失败");
        });
      console.log("Adding project:", this.form);
      // 重置表单
      this.form = {
        category: "",
        productName: "",
        standardNumber: "",
        standardName: "",
      };
      // 关闭弹窗
      this.dialogVisible = false;
    },

    triggerFileInput() {
      // 触发隐藏的文件输入元素的点击事件
      this.$refs.fileInput.value = null; // 清空文件输入，以便可以选择相同的文件
      this.$refs.fileInput.click();
    },
    importFromExcel(event) {
      const file = event.target.files[0];
      if (!file) {
        return;
      }

      // 验证文件类型
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                      file.type === 'application/vnd.ms-excel';
      if (!isExcel) {
        this.$message.error('只能上传Excel文件！');
        return;
      }

      // 验证文件大小（例如限制为10MB）
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error('文件大小不能超过 10MB!');
        return;
      }

      const formData = new FormData();
      formData.append('formData', file);
      
      this.isUploading = true;

      this.$http.post('/excelAddToStandard', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then(response => {
        if (response.data) {
          this.$message({
            message: 'Excel导入成功！',
            type: 'success'
          });
          
          // 刷新数据
          this.$http.get("/host").then((result) => {
            this.items = result.data;
          });
        } else {
          throw new Error('导入失败');
        }
      })
      .catch(error => {
        console.error('导入失败:', error);
        this.$message.error('Excel导入失败，请检查文件格式！');
      })
      .finally(() => {
        this.isUploading = false;
        // 清空文件输入，允许重复选择相同文件
        this.$refs.fileInput.value = null;
      });
    },
    
    showItem(item) {
      this.$router.push({
        name: 'project-manage',
        params: {
          param: item.staId,
          standardName: item.staName
        }
      });
    },
    deleteItem(item) {
      console.log("删除操作", item.staId);

      // 删除项目的逻辑
      if (confirm("确定要删除此项目吗？")) {
        const index = this.items.indexOf(item);
        if (index !== -1) {
          this.$http
            .delete("/DeleteStandard", {
              params: {
                staId: item.staId,
              },
            })
            .then((result) => {
              console.log(result);
              this.$message.success("删除成功");
              this.fetchData(); // 删除成功后刷新数据
            })
            .catch((error) => {
              console.error("删除失败:", error);
              this.$message.error("删除失败");
            });
        }
      }
    },
    showSample(item) {
      this.$router.push({
        name: "sample_check",
        params: { 
          param: item.staId,
          standardName: item.staName  // 添加标准名称参数
        },
      });
    },
    toggleSelectAll() {
      if (this.selectAll) {
        this.selectedItems = this.filteredItems.map((item) => item.staId);
      } else {
        this.selectedItems = [];
      }
    },
    batchDelete() {
      if (!this.selectedItems.length) {
        this.$message.warning('请选择要删除的项目')
        return
      }

      if (confirm(`确定要删除选中的 ${this.selectedItems.length} 项吗？`)) {
        console.log('准备删除的项目IDs:', this.selectedItems)
        
        this.$http
          .delete('/DeleteMoreStandard', {
            data: this.selectedItems  // 直接发送数组作为请求体
          })
          .then((response) => {
            console.log('删除响应:', response)
            if (response.data === '删除成功') {
              this.$message.success('批量删除成功')
              this.selectedItems = []
              this.selectAll = false
              this.fetchData()
            } else {
              this.$message.error(response.data || '批量删除失败')
            }
          })
          .catch((error) => {
            console.error('批量删除失败:', error)
            this.$message.error('批量删除失败')
          })
      }
    },
    exportToExcel() {
      // 准备导出数据
      const data = this.filteredItems.map((item, index) => ({
        序号: index + 1,
        大类: item.staType,
        产品名: item.projectName,
        "标准编号（含年号）": item.staGB,
        标准名称: item.staName,
      }));

      // 创建工作表
      const ws = XLSX.utils.json_to_sheet(data);

      // 设置列宽
      const colWidths = [
        { wch: 8 }, // 序号
        { wch: 15 }, // 大类
        { wch: 20 }, // 产品名
        { wch: 25 }, // 标准编号
        { wch: 30 }, // 标准名称
      ];
      ws["!cols"] = colWidths;

      // 创建工作簿并添加工作表
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "标准管理");

      // 导出文件
      XLSX.writeFile(wb, `标准管理表_${new Date().toLocaleDateString()}.xlsx`);
    },
    fetchData() {
      this.$http
        .get("/host")
        .then((result) => {
          console.log(result.data);
          this.items = result.data;
        })
        .catch((error) => {
          console.error("获取数据失败:", error);
          this.$message.error("获取数据失败");
        });
    },
  },
};
</script>

<style scoped>
.standard-management-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 25px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 搜索区域样式 */
.search-and-buttons {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.search-input {
  flex-grow: 1;
  padding: 12px 15px;
  border: 2px solid #e8e8e8;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s;
}

.search-input:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 按钮组样式 */
.buttons {
  display: flex;
  gap: 10px;
}

.buttons button {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-button {
  background-color: #409eff;
  color: white;
}

.import-excel-button {
  background-color: #67c23a;
  color: white;
}

.export-excel-button {
  background-color: #909399;
  color: white;
}

.batch-delete-button {
  background-color: #f56c6c;
  color: white;
}

.buttons button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.buttons button:disabled {
  background-color: #909399;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 表格样式 */
.standards-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 0 0 1px #ebeef5;
}

.standards-table th {
  background-color: #f5f7fa;
  padding: 15px 12px;
  font-weight: 600;
  color: #606266;
  border-bottom: 2px solid #ebeef5;
  text-align: center;
}

.standards-table td {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  color: #606266;
  text-align: center;
}

.standards-table tr:hover {
  background-color: #f5f7fa;
}

/* 操作链接样式 */
.action-link {
  margin: 0 8px;
}

.action-divider {
  color: #dcdfe6;
  margin: 0 8px;
}

.view-link {
  color: #409eff;
}

.delete-link {
  color: #f56c6c;
}

.sample-link {
  color: #e6a23c;
}

.view-link:hover,
.delete-link:hover,
.sample-link:hover {
  opacity: 0.8;
  text-decoration: underline;
}

/* 复选框样式 */
input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__body) {
  padding: 30px 20px;
}

:deep(.el-dialog__footer) {
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-button) {
  padding: 10px 20px;
  font-weight: 500;
}

/* 添加标题样式 */
.page-title {
  font-size: 24px;
  color: #303133;
  margin-bottom: 25px;
  font-weight: 600;
  position: relative;
  padding-left: 15px;
  border-left: 4px solid #409eff;
  display: flex;
  align-items: center;
}

.page-title::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -8px;
  width: 100%;
  height: 1px;
  background: linear-gradient(to right, #409eff, transparent);
}
</style>
